package com.project.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.GradeBean;
import com.project.bean.RoleBean;
import com.project.mapper.IGradeMapper;
import com.project.mapper.IRoleMapper;
import com.project.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private IRoleMapper roleMapper;
    @Autowired
    private IGradeMapper gradeMapper;

    @Override
    public List<RoleBean> findAll() {

        return roleMapper.selectList(null);
    }

    @Override
    public IPage<RoleBean> cutByItem(Integer pageNO) {
        return roleMapper.selectPage(new Page<>(pageNO, 5), null);
    }

    @Override
    public RoleBean findById(Integer id) {
        //查询角色
        RoleBean role = roleMapper.selectById(id);

        //查询角色权限
        List<GradeBean> gradeList = gradeMapper.findByRoleList(new Integer[]{id});
        role.setGradeList(gradeList);
        return role;
    }

    @Override
    public void add(RoleBean role,Integer[] gradeIdArr) {
        roleMapper.insert(role);
        roleMapper.addGrades(role.getId(), gradeIdArr);
    }

    @Override
    public void updateGrades(Integer id, Integer[] gradeIdArr) {
        roleMapper.delGrades(id);
        roleMapper.addGrades(id,gradeIdArr);
    }
    @Override
    public void del(Integer id) {
        //删除角色权限
        roleMapper.delGrades(id);
        //删除用户拥有的角色
        roleMapper.findByUserId(id);
        //删除角色
        roleMapper.deleteById(id);

    }
}
